<template>
  <div class="page-container">
    <OpinionVerticalTabNav />
    
    <div class="public-opinion-container">
      <!-- 搜索和操作区域 -->
      <div class="filter-area">
        <div class="search-area">
          <el-input
            v-model="searchValue"
            placeholder="请输入舆情标题搜索"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="operation-area">
          <!-- <el-button type="primary" @click="navigateToSource" class="category-button">
            <el-icon><Link /></el-icon>舆情来源管理
          </el-button>
          <el-button type="success" @click="navigateToHotWords" class="category-button">
            <el-icon><Collection /></el-icon>舆情热词管理
          </el-button> -->
          <el-button class="custom-button primary-button" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增数据
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        height="calc(100vh - 250px)"
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="标题" prop="title" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="title-cell" @click="showContent(scope.row)">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="来源" prop="sourceId" width="120" align="center">
          <template #default="scope">
            <span class="source-name">
              {{ getSourceName(scope.row.sourceId) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="性质" prop="sentimentType" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getSentimentType(scope.row.sentimentType)">
              {{ scope.row.sentimentType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" prop="publishTime" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="热度" prop="hotIndex" width="100" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.hotIndexValue"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="warning" link @click="handleChangeStatus(scope.row)">更新状态</el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增舆情' : '编辑舆情'"
        width="60%"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="舆情标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入舆情标题" />
          </el-form-item>
          <el-form-item label="舆情来源" prop="sourceId">
            <el-select v-model="form.sourceId" placeholder="请选择舆情来源" style="width: 100%">
              <el-option
                v-for="item in sourceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="舆情内容" prop="content">
            <el-input
              type="textarea"
              v-model="form.content"
              :rows="5"
              placeholder="请输入舆情详细内容"
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性质" prop="sentimentType">
                <el-select v-model="form.sentimentType" placeholder="请选择舆情性质" style="width: 100%">
                  <el-option label="正面" value="正面" />
                  <el-option label="负面" value="负面" />
                  <el-option label="中性" value="中性" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择舆情状态" style="width: 100%">
                  <el-option label="未处理" value="未处理" />
                  <el-option label="已处理" value="已处理" />
                  <el-option label="跟进中" value="跟进中" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发布时间" prop="publishTime">
                <el-date-picker
                  v-model="form.publishTime"
                  type="datetime"
                  placeholder="选择发布时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="热度指数" prop="hotIndex">
                <el-slider
                  v-model="form.hotIndex"
                  :min="1"
                  :max="5"
                  :step="1"
                  :marks="{1:'低', 3:'中', 5:'高'}"
                  :show-tooltip="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 内容查看弹窗 -->
      <el-dialog
        v-model="contentDialogVisible"
        :title="currentOpinion.title"
        width="60%"
        destroy-on-close
      >
        <div class="content-view">
          <div class="content-meta">
            <div class="meta-item">
              <span class="label">来源：</span>
              <span class="value">{{ getSourceName(currentOpinion.sourceId) }}</span>
            </div>
            <div class="meta-item">
              <span class="label">发布时间：</span>
              <span class="value">{{ formatDateTime(currentOpinion.publishTime) }}</span>
            </div>
            <div class="meta-item">
              <span class="label">性质：</span>
              <el-tag :type="getSentimentType(currentOpinion.sentimentType)" size="small">
                {{ currentOpinion.sentimentType }}
              </el-tag>
            </div>
            <div class="meta-item">
              <span class="label">热度：</span>
              <el-rate
                v-model="currentOpinion.hotIndexValue"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
            </div>
            <div class="meta-item">
              <span class="label">状态：</span>
              <el-tag :type="getStatusType(currentOpinion.status)" size="small">
                {{ currentOpinion.status }}
              </el-tag>
            </div>
          </div>
          <div class="content-body">
            <p>{{ currentOpinion.content }}</p>
          </div>
        </div>
      </el-dialog>

      <!-- 状态更新弹窗 -->
      <el-dialog
        v-model="statusDialogVisible"
        title="更新舆情状态"
        width="40%"
        destroy-on-close
      >
        <el-form
          ref="statusFormRef"
          :model="statusForm"
          :rules="statusRules"
          label-width="120px"
          class="status-form"
        >
          <el-form-item label="当前状态" prop="currentStatus">
            <el-tag :type="getStatusType(statusForm.currentStatus)">
              {{ statusForm.currentStatus }}
            </el-tag>
          </el-form-item>
          <el-form-item label="新状态" prop="status">
            <el-select v-model="statusForm.status" placeholder="请选择舆情状态" style="width: 100%">
              <el-option label="未处理" value="未处理" />
              <el-option label="已处理" value="已处理" />
              <el-option label="跟进中" value="跟进中" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="statusDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitStatusChange">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Link, Collection } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { 
  getPublicOpinionInfoList, 
  getPublicOpinionInfoById, 
  addPublicOpinionInfo, 
  updatePublicOpinionInfo, 
  deletePublicOpinionInfo,
  getPublicOpinionList 
} from "@/api/bridge/bisc/public-opinion";
import OpinionVerticalTabNav from './components/OpinionVerticalTabNav.vue';

// 路由
const router = useRouter();

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchValue = ref("");

// 舆情来源选项
const sourceOptions = ref<{value: string, label: string}[]>([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: "",
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const contentDialogVisible = ref(false);
const statusDialogVisible = ref(false);

// 当前查看的舆情
const currentOpinion = ref<any>({});

// 处理热度显示
const processTableData = (data: any[]) => {
  return data.map(item => {
    return {
      ...item,
      hotIndexValue: item.hotIndex || 1
    };
  });
};

// 表单数据
const formRef = ref();
const form = ref({
  id: "",
  title: "",
  sourceId: "",
  content: "",
  sentimentType: "",
  publishTime:dayjs().format('YYYY-MM-DD HH:mm:ss'),
  hotIndex: 3,
  status: "未处理",
});

// 状态更新表单
const statusFormRef = ref();
const statusForm = ref({
  id: "",
  currentStatus: "",
  status: "",
});

// 表单校验规则
const rules = {
  title: [{ required: true, message: "请输入舆情标题", trigger: "blur" }],
  sourceId: [{ required: true, message: "请选择舆情来源", trigger: "change" }],
  content: [{ required: true, message: "请输入舆情内容", trigger: "blur" }],
  sentimentType: [{ required: true, message: "请选择舆情性质", trigger: "change" }],
  publishTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
  status: [{ required: true, message: "请选择舆情状态", trigger: "change" }],
};

// 状态表单校验规则
const statusRules = {
  status: [{ required: true, message: "请选择舆情状态", trigger: "change" }],
};

// 格式化日期时间
const formatDateTime = (date: string | number | Date) => {
  if (!date) return "-";
  
  // 如果是时间戳字符串，先转换为数字
  if (typeof date === 'string' && /^\d+$/.test(date)) {
    return dayjs(parseInt(date)).format('YYYY-MM-DD HH:mm:ss');
  }
  
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取舆情性质对应的标签类型
const getSentimentType = (type: string) => {
  switch (type) {
    case "正面":
      return "success";
    case "负面":
      return "danger";
    case "中性":
      return "info";
    default:
      return "info";
  }
};

// 获取舆情状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "未处理":
      return "danger";
    case "已处理":
      return "success";
    case "跟进中":
      return "warning";
    default:
      return "info";
  }
};

// 获取舆情来源名称
const getSourceName = (sourceId: string | number) => {
  if (!sourceId) return "未知来源";
  
  const source = sourceOptions.value.find(item => item.value === sourceId);
  return source ? source.label : "未知来源";
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    queryParams.pageNum = currentPage.value;
    queryParams.pageSize = pageSize.value;
    queryParams.title = searchValue.value;

    const res = await getPublicOpinionInfoList(queryParams);
    tableData.value = processTableData(res.rows || []);
    total.value = res.total || 0;
  } catch (error) {
    console.error("获取舆情列表失败:", error);
    ElMessage.error("获取舆情列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取舆情来源
const getSourceOptions = async () => {
  try {
    const res = await getPublicOpinionList({
      pageNum: 1,
      pageSize: 100
    });
    sourceOptions.value = (res.rows || []).map(item => ({
      value: item.id,
      label: item.sourceName
    }));
  } catch (error) {
    console.error("获取舆情来源失败:", error);
    ElMessage.error("获取舆情来源失败");
  }
};

// 跳转到舆情来源管理
const navigateToSource = () => {
  router.push('/basic-data/public-opinion-source');
};

// 跳转到舆情热词管理
const navigateToHotWords = () => {
  router.push('/basic-data/public-opinion-hotwords');
};

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  form.value = {
    id: "",
    title: "",
    sourceId: "",
    content: "",
    sentimentType: "",
    publishTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    hotIndex: 3,
    status: "未处理",
  };
  dialogVisible.value = true;
};

// 查看详情
const handleView = async (row: any) => {
  try {
    loading.value = true;
    const res = await getPublicOpinionInfoById(row.id);
    showContent(res.data);
  } catch (error) {
    console.error("获取舆情详情失败:", error);
    ElMessage.error("获取舆情详情失败");
  } finally {
    loading.value = false;
  }
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    loading.value = true;
    const res = await getPublicOpinionInfoById(row.id);
    dialogType.value = "edit";
    
    // 处理时间字段，确保在表单中正确显示
    const data = { ...res.data };
    
    // 如果publishTime是时间戳字符串，将其转换为日期对象
    if (data.publishTime && typeof data.publishTime === 'string' && /^\d+$/.test(data.publishTime)) {
      data.publishTime = new Date(parseInt(data.publishTime));
    }
    
    form.value = data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取舆情详情失败:", error);
    ElMessage.error("获取舆情详情失败");
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该舆情信息吗？", "警告", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deletePublicOpinionInfo(row.id);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        console.error("删除舆情失败:", error);
        ElMessage.error("删除舆情失败");
      }
    })
    .catch(() => {});
};

// 展示内容
const showContent = (row: any) => {
  currentOpinion.value = {
    ...row,
    hotIndexValue: row.hotIndex || 1
  };
  contentDialogVisible.value = true;
};

// 更改状态
const handleChangeStatus = (row: any) => {
  statusForm.value = {
    id: row.id,
    currentStatus: row.status,
    status: row.status
  };
  statusDialogVisible.value = true;
};

// 提交状态更改
const submitStatusChange = async () => {
  if (!statusFormRef.value) return;
  await statusFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const data = {
          id: statusForm.value.id,
          status: statusForm.value.status
        };
        await updatePublicOpinionInfo(data);
        ElMessage.success("状态更新成功");
        statusDialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("状态更新失败:", error);
        ElMessage.error("状态更新失败");
      }
    }
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 处理时间字段
        let submitData = { ...form.value };
        
        // 确保publishTime是时间戳字符串
        if (submitData.publishTime instanceof Date) {
          submitData.publishTime = submitData.publishTime.getTime().toString();
        } else if (submitData.publishTime && typeof submitData.publishTime === 'string' && !(/^\d+$/.test(submitData.publishTime))) {
          // 如果是日期字符串但不是时间戳
          submitData.publishTime = new Date(submitData.publishTime).getTime().toString();
        }
        
        if (dialogType.value === "add") {
          await addPublicOpinionInfo(submitData);
          ElMessage.success("新增成功");
        } else {
          await updatePublicOpinionInfo(submitData);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

onMounted(() => {
  getSourceOptions();
  getList();
});
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.public-opinion-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .search-input {
    width: 300px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-area {
  display: flex;
  gap: 12px;

  .category-button {
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
    }
  }

  .custom-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;

    &::before {
      content: "";
      position: absolute;
      top: 50%;
      left: 50%;
      width: 0;
      height: 0;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.6s ease, height 0.6s ease;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

      &::before {
        width: 300px;
        height: 300px;
      }
    }

    &:active {
      transform: translateY(1px);
    }
  }

  .primary-button {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;

    &:hover {
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
  }
}

.title-cell {
  cursor: pointer;
  color: var(--el-color-primary);
  
  &:hover {
    text-decoration: underline;
  }
}

.source-name {
  padding: 2px 6px;
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-radius: 4px;
  font-size: 12px;
}

.content-view {
  .content-meta {
    margin-bottom: 20px;
    padding: 15px;
    background-color: var(--el-bg-color-page);
    border-radius: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    
    .meta-item {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-right: 20px;
      
      .label {
        color: var(--el-text-color-secondary);
      }
      
      .value {
        color: var(--el-text-color-primary);
        font-weight: 500;
      }
    }
  }
  
  .content-body {
    line-height: 1.8;
    color: var(--el-text-color-primary);
    margin-top: 20px;
    padding: 20px;
    border-left: 4px solid var(--el-color-primary-light-5);
    background-color: var(--el-color-primary-light-9);
    border-radius: 0 8px 8px 0;
  }
}

.status-form {
  .el-tag {
    padding: 2px 8px;
    height: 26px;
    line-height: 22px;
  }
}
</style>